package com.gurun.codes.business.home;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.google.gson.reflect.TypeToken;
import com.gurun.base.Logger;
import com.gurun.base.utils.CommonUtils;
import com.gurun.camera.device.VideoActivity;
import com.gurun.codes.App;
import com.gurun.codes.R;
import com.gurun.codes.business.common_alarm.CommonAlarmActivity;
import com.gurun.codes.business.curtain.CurtainActivity;
import com.gurun.codes.business.door_window.DoorWindowActivity;
import com.gurun.codes.business.human_body.HumanBodyActivity;
import com.gurun.codes.business.natural_gas.NaturalGasActivity;
import com.gurun.codes.business.smog.SmogActivity;
import com.gurun.codes.business.temperature_humidity.TemperatureHumidityActivity;
import com.gurun.codes.business.water.WaterEnterActivity;
import com.gurun.codes.contract.base.BasePresenter;
import com.gurun.codes.contract.base.view.RxView;
import com.gurun.codes.utils.Constants;
import com.gurun.codes.utils.Md5;
import com.gurun.model.base.ResultObserver;
import com.gurun.model.base.RetrofitManager;
import com.gurun.model.bean.ApiResult;
import com.gurun.model.bean.BaseRequestBean;
import com.gurun.model.bean.home.GetHomeDeviceListRequestBean;
import com.gurun.model.bean.home.GetHomeDeviceListResultBean;
import com.gurun.model.bean.home.GetHomeListResultBean;
import com.gurun.model.bean.home.GetRoomDeviceListRequestBean;
import com.gurun.model.bean.home.GetRoomDeviceListResultBean;
import com.gurun.model.bean.home.GetRoomListRequestBean;
import com.gurun.model.bean.home.GetRoomListResultBean;
import com.gurun.model.bean.home.GetTaskListRequestBean;
import com.gurun.model.bean.home.GetTaskListResultBean;
import com.gurun.model.bean.home.GetWeatherByIpRequestBean;
import com.gurun.model.bean.home.GetWeatherByIpResultBean;
import com.gurun.model.bean.user.LoginRequestBean;
import com.gurun.model.bean.user.LoginResultBean;
import com.gurun.model.service.HomeService;
import com.gurun.model.service.UserService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public interface MainActivityContract {

    interface MainActivityView extends RxView {

        void onComplete();

        void onLoading();

        void onHomeListLoaded(GetHomeListResultBean datas);

        void onRoomListLoaded(GetRoomListResultBean datas);

        void onWeatherLoaded(GetWeatherByIpResultBean datas);

        void onRoomDeviceListLoaded(GetRoomDeviceListResultBean datas);

        void onError(String msg);

        void onHomeItemSelected(GetHomeListResultBean.SmartHomeListBean smartHomeListBean);

        void onRoomItemSelected(GetRoomListResultBean.SmartRoomListBean smartRoomListBean);

        void onTimeChanged();

        void onTaskListLoaded(GetTaskListResultBean datas);

        void onCommonDeviceListLoaded(GetRoomDeviceListResultBean datas);
    }

    class MainActivityViewPresenter extends BasePresenter<MainActivityView> {

        private Context mContext;

        public MainActivityViewPresenter(Context context) {
            this.mContext = context;
        }

        public void getHomeList() {
            BaseRequestBean requestBean = new BaseRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());

            RetrofitManager.getInstance().createApiService(HomeService.class)
                    .getHomeList(requestBean)
                    .compose(getView().<GetHomeListResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetHomeListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetHomeListResultBean result, String msg) {
                            getView().onHomeListLoaded(result);
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }

        public void getRoomList(final int homeId) {
            final GetRoomListRequestBean requestBean = new GetRoomListRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());
            requestBean.setHomeId(homeId);

            RetrofitManager.getInstance().createApiService(HomeService.class)
                    .getRoomList(requestBean)
                    .compose(getView().<GetRoomListResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetRoomListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetRoomListResultBean result, String msg) {
                            getView().onRoomListLoaded(result);
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }

        public void getRoomDeviceList(int homeId, int roomId) {
            GetRoomDeviceListRequestBean requestBean = new GetRoomDeviceListRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());
            requestBean.setHomeId(homeId);
            requestBean.setRoomId(roomId);
            requestBean.setDeviceFlag(0);

            RetrofitManager.getInstance().createApiService(HomeService.class)
                    .getRoomDeviceList(requestBean)
                    .compose(getView().<GetRoomDeviceListResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetRoomDeviceListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetRoomDeviceListResultBean result, String msg) {
                            getView().onRoomDeviceListLoaded(result);
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }

        public void getWeatherByIp() {
            Single.create(new SingleOnSubscribe<String>() {
                @Override
                public void subscribe(SingleEmitter<String> e) {
                    String ip = CommonUtils.getNetIp();
                    e.onSuccess(ip);
                }
            }).subscribeOn(Schedulers.io())
                    .flatMap(new Function<String, SingleSource<GetWeatherByIpResultBean>>() {
                        @Override
                        public SingleSource<GetWeatherByIpResultBean> apply(String ip) throws Exception {
                            GetWeatherByIpRequestBean requestBean = new GetWeatherByIpRequestBean();
                            requestBean.setVersion(Constants.HTTP_VERSION);
                            requestBean.setUserId(App.getInstance().getLoginUserId());
                            requestBean.setToken(App.getInstance().getLoginToken());
                            requestBean.setIp(ip);
                            return RetrofitManager.getInstance().createApiService(HomeService.class)
                                    .getWeatherByIp(requestBean);
                        }
                    }).compose(getView().<GetWeatherByIpResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetWeatherByIpResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetWeatherByIpResultBean result, String msg) {
                            getView().onWeatherLoaded(result);
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }


        public void getSceneList(long homeId) {
            final GetTaskListRequestBean requestBean = new GetTaskListRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());
            requestBean.setHomeId(homeId);
            requestBean.setTvSync(1);

            RetrofitManager.getInstance().createApiService(HomeService.class)
                    .getSmartTaskList(requestBean)
                    .compose(getView().<GetTaskListResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetTaskListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetTaskListResultBean result, String msg) {
                            getView().onTaskListLoaded(result);
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }

        public void getCommonDeviceList(int homeId) {
            GetRoomDeviceListRequestBean requestBean = new GetRoomDeviceListRequestBean();
            requestBean.setVersion(Constants.HTTP_VERSION);
            requestBean.setUserId(App.getInstance().getLoginUserId());
            requestBean.setToken(App.getInstance().getLoginToken());
            requestBean.setHomeId(homeId);
            requestBean.setRoomId(GetRoomDeviceListRequestBean.ALL_ROOM);
            requestBean.setDeviceFlag(GetRoomDeviceListRequestBean.COMMON_DEVICE_FLAG);

            RetrofitManager.getInstance().createApiService(HomeService.class)
                    .getRoomDeviceList(requestBean)
                    .compose(getView().<GetRoomDeviceListResultBean>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new ResultObserver<GetRoomDeviceListResultBean>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(mContext.getString(R.string.common_connect_server_failed));
                        }

                        @Override
                        public void onLoaded() {
                            getView().onComplete();
                        }

                        @Override
                        public void onSuccess(GetRoomDeviceListResultBean result, String msg) {
                            getView().onCommonDeviceListLoaded(result);
                        }

                        @Override
                        public void onApiError(ApiResult result) {
                            if (result != null) {
                                getView().onError(result.getRetMsg());
                            } else {
                                getView().onError(mContext.getString(R.string.common_connect_server_failed));
                            }
                        }
                    }));
        }


        Handler timeHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                getView().onTimeChanged();
                timeHandler.sendEmptyMessageDelayed(1,60*1000);
            }
        };

        public void startUpdateTime(){
            timeHandler.sendEmptyMessage(1);
        }

        public void stopUpdateTime(){
            timeHandler.removeMessages(1);
        }

        public enum DeviceType {
            DEVICE_TYPE_BLE_LAMP(1, "蓝牙智能灯"),
            DEVICE_TYPE_WATCH(2, "智能手表"),
            DEVICE_TYPE_PET(3, "宠物定位"),
            DEVICE_TYPE_WIFI_LAMP(4, "WIFI智能灯"),
            DEVICE_TYPE_ZIGBEE_LAMP(5, "Zigbee智能灯"),
            DEVICE_TYPE_PREPAY_WATER_METER(6, "蓝牙水表"),
            DEVICE_TYPE_AFTERPAY_WATER_METER(7, "后付费智能水表"),
            DEVICE_TYPE_PREPAY_GAS_METER(8, "蓝牙燃气表"),
            DEVICE_TYPE_AFTERPAY_GAS_METER(9, "后付费智能燃气表"),
            DEVICE_TYPE_CONTROLLER(10, "智能控制器"),
            DEVICE_TYPE_REMOTE_WATER_METER(11, "LoRa水表"),
            DEVICE_TYPE_REMOTE_GAS_METER(12, "LoRa燃气表"),
            DEVICE_TYPE_REMOTE_CONTROLER(13, "智能遥控器"),
            DEVICE_TYPE_EPO_LOCATOR(14, "EPO车载定位器"),
            DEVICE_TYPE_MACHINE_WATER_METER(15, "机械水表"),
            DEVICE_TYPE_MACHINE_GAS_METER(16, "机械燃气表"),
            DEVICE_TYPE_IC_WATER_METER(17, "IC卡水表"),
            DEVICE_TYPE_IC_GAS_METER(18, "IC卡燃气表"),
            DEVICE_TYPE_ELECTRIC_METER(19, "蓝牙电表"),
            DEVICE_TYPE_REMOTE_ELECTRIC_METER(20, "LoRa电表"),
            DEVICE_TYPE_ZIGBEE_LINUX_HOME_GATEWAY(21, "网关型家庭网关"),
            DEVICE_TYPE_ZIGBEE_MAGNET(22, "门窗传感器"),
            DEVICE_TYPE_ZIGBEE_MOTION(23, "人体传感器"),
            DEVICE_TYPE_ZIGBEE_SWITCH(24, "无线开关"),
            DEVICE_TYPE_ZIGBEE_WEATHER(25, "温湿度传感器"),
            DEVICE_TYPE_ZIGBEE_CURTAIN(26, "电动窗帘传感器"),
            DEVICE_TYPE_ZIGBEE_SMOKE(27, "烟雾传感器"),
            DEVICE_TYPE_ZIGBEE_WLEAK(28, "水浸传感器"),
            DEVICE_TYPE_ZIGBEE_NATGAS(29, "可燃气体传感器"),
            DEVICE_TYPE_ZIGBEE_PLUG(30, "智能插座"),
            DEVICE_TYPE_ZIGBEE_PLUG86(31, "86暗盒"),//墙壁插座
            DEVICE_TYPE_ZIGBEE_NEUTRAL1(32, "86单火开关单键设备"),
            DEVICE_TYPE_ZIGBEE_NEUTRAL2(33, "86单火开关双键设备"),
            DEVICE_TYPE_ZIGBEE_SWITCH861(34, "86无线开关单键设备"),
            DEVICE_TYPE_ZIGBEE_SWITCH862(35, "86无线开关双键设备"),
            DEVICE_TYPE_YKT_WATER_METER(36, "IC卡一卡通水表"),
            DEVICE_TYPE_ZIGBEE_STB_HOME_GATEWAY(37, "机顶盒型家庭网关"),
            DEVICE_TYPE_BLE_SMART_LOCK(38, "蓝牙智能锁"),
            DEVICE_TYPE_QSIC_WATER_METER(39, "轻松阶梯IC卡水表"),
            DEVICE_TYPE_QSYKT_WATER_METER(40, "轻松一卡通IC卡水表"),
            DEVICE_TYPE_ZIGBEE_SMART_LOCK(41, "Zigbee智能锁"),
            DEVICE_TYPE_ZIGBEE_CUBE(42, "魔方控制器"),
            DEVICE_TYPE_ZIGBEE_CTRLLN1(43, "零火开关单键"),
            DEVICE_TYPE_ZIGBEE_CTRLLN2(44, "零火开关双键"),
            DEVICE_TYPE_WIFI_CAMERA(45, "九州摄像头");

            private final int deviceType;
            private final String deviceName;

            public int getDeviceType() {
                return deviceType;
            }

            public String getDeviceName() {
                return deviceName;
            }

            DeviceType(int id, String name) {
                deviceType = id;
                deviceName = name;
            }
        }

        public void onDeviceClicked(GetRoomDeviceListResultBean.FamilyDevice familyDevice, String currentRoomName) {
            if (DeviceType.DEVICE_TYPE_ZIGBEE_MAGNET.getDeviceType() == familyDevice.getDeviceType()) {
                //门窗传感器
                DoorWindowActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_SMOKE.getDeviceType() == familyDevice.getDeviceType()) {
                //烟雾报警器
                SmogActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_WEATHER.getDeviceType() == familyDevice.getDeviceType()) {
                //温湿度传感器
                TemperatureHumidityActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_MOTION.getDeviceType() == familyDevice.getDeviceType()) {
                //人体传感器
                HumanBodyActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_WLEAK.getDeviceType() == familyDevice.getDeviceType()) {
                //水浸传感器
                WaterEnterActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_NATGAS.getDeviceType() == familyDevice.getDeviceType()) {
                //门窗传感器
                NaturalGasActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_WIFI_CAMERA.getDeviceType() == familyDevice.getDeviceType()) {
                //摄像头
                VideoActivity.startActivity(mContext, familyDevice.getShortId(), currentRoomName);
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_CURTAIN.getDeviceType() == familyDevice.getDeviceType()) {
                //窗帘
                CurtainActivity.startActivity(mContext, familyDevice.getDeviceId());
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH.getDeviceType() == familyDevice.getDeviceType()
                    || DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH861.getDeviceType() == familyDevice.getDeviceType()
                    || DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH862.getDeviceType() == familyDevice.getDeviceType()
                    ) {
                //无线开关
                int bgRes = R.mipmap.bg_switch;
                int emptyRes = R.mipmap.ic_empty_door_window;
                String title = familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH.getDeviceName() :
                        familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH861.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH861.getDeviceName() :
                                familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH862.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_SWITCH862.getDeviceName() :
                                        "";
                CommonAlarmActivity.startActivity(mContext, familyDevice.getDeviceId(), title, bgRes, emptyRes);

            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_PLUG.getDeviceType() == familyDevice.getDeviceType()
                    || DeviceType.DEVICE_TYPE_ZIGBEE_PLUG86.getDeviceType() == familyDevice.getDeviceType()
                    ) {
                //插座
                int bgRes = R.mipmap.bg_socket;
                int emptyRes = R.mipmap.ic_empty_door_window;
                String title = familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_PLUG.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_PLUG.getDeviceName() : DeviceType.DEVICE_TYPE_ZIGBEE_PLUG86.getDeviceName();
                CommonAlarmActivity.startActivity(mContext, familyDevice.getDeviceId(), title, bgRes, emptyRes);
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_NEUTRAL1.getDeviceType() == familyDevice.getDeviceType()
                    || DeviceType.DEVICE_TYPE_ZIGBEE_NEUTRAL2.getDeviceType() == familyDevice.getDeviceType()
                    || DeviceType.DEVICE_TYPE_ZIGBEE_CTRLLN1.getDeviceType() == familyDevice.getDeviceType()
                    || DeviceType.DEVICE_TYPE_ZIGBEE_CTRLLN2.getDeviceType() == familyDevice.getDeviceType()

                    ) {
                //墙壁开关
                int bgRes = R.mipmap.bg_switch;
                int emptyRes = R.mipmap.ic_empty_door_window;
                String title = familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_NEUTRAL1.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_NEUTRAL1.getDeviceName() :
                        familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_NEUTRAL2.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_NEUTRAL2.getDeviceName() :
                                familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_CTRLLN1.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_CTRLLN1.getDeviceName() :
                                        familyDevice.getDeviceType() == DeviceType.DEVICE_TYPE_ZIGBEE_CTRLLN2.getDeviceType() ? DeviceType.DEVICE_TYPE_ZIGBEE_CTRLLN2.getDeviceName() :
                                                "";
                CommonAlarmActivity.startActivity(mContext, familyDevice.getDeviceId(), title, bgRes, emptyRes);
            } else if (DeviceType.DEVICE_TYPE_ZIGBEE_CUBE.getDeviceType() == familyDevice.getDeviceType()) {
                //魔方
                int bgRes = -1;
                int emptyRes = R.mipmap.ic_empty_door_window;
                String title = DeviceType.DEVICE_TYPE_ZIGBEE_CUBE.getDeviceName();
                CommonAlarmActivity.startActivity(mContext, familyDevice.getDeviceId(), title, bgRes, emptyRes);
            }
        }

    }
}
